import { Request, Response } from 'express';
import { contentDisplayService } from './service';
import { AuthRequest } from '../../types/auth';
import { ApiResponse } from '../../types/page';
import { ContentDisplay, ContentCategory, ContentType } from '../../entities/ContentDisplay';

type ContentListResponse = {
  records: ContentDisplay[];
  total: number;
  size: number;
  current: number;
  pages: number;
};
/**
 * 获取风景内容列表
 */
export const getSceneryList = async (req: AuthRequest, res: Response) => {
  try {
    const current = Number(req.query.page) || 1;
    const size = Number(req.query.size) || 10;
    const type = req.query.type !== undefined ? Number(req.query.type) : undefined;
    const isActive = req.query.isActive !== undefined ? req.query.isActive === 'true' : undefined;
    const title = req.query.title as string;
    
    const { contents, total } = await contentDisplayService.getContentList({
      page: current,
      pageSize: size,
      category: ContentCategory.SCENERY,
      type,
      isActive,
      title
    });
    
    const response: ApiResponse<ContentListResponse> = {
      success: true,
      data: {
        records: contents,
        total,
        size,
        current,
        pages: Math.ceil(total / size)
      }
    };
    
    res.json(response);
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '获取风景内容列表失败',
      error: error.message
    });
  }
};

/**
 * 创建风景内容
 */
export const createScenery = async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.user?.id;
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }
    
    const contentData = req.body;
    
    // 设置固定类别为风景
    contentData.category = ContentCategory.SCENERY;
    
    // 验证必填字段
    if (!contentData.type || !contentData.title) {
      return res.status(400).json({
        success: false,
        message: '内容类型和标题为必填项'
      });
    }
    
    // 验证内容类型是否有效
    if (!Object.values(ContentType).includes(contentData.type)) {
      return res.status(400).json({
        success: false,
        message: '无效的内容类型'
      });
    }
    
    // 验证内容类型和URL是否匹配
    if ((contentData.type === ContentType.IMAGE) && !contentData.imageUrl) {
      return res.status(400).json({
        success: false,
        message: '图片类型内容必须提供图片URL'
      });
    }
    
    if (contentData.type === ContentType.VIDEO && !contentData.videoUrl) {
      return res.status(400).json({
        success: false,
        message: '视频类型内容必须提供视频URL'
      });
    }
    
    const content = await contentDisplayService.createContent(contentData, userId);
    
    res.json({
      success: true,
      message: '创建风景内容成功',
      data: content
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '创建风景内容失败',
      error: error.message
    });
  }
};

/**
 * 更新风景内容
 */
export const updateScenery = async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.user?.id;
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }
    
    const id = req.params.id;
    const contentData = req.body;
    
    // 确保不能修改类别
    delete contentData.category;
    
    // 验证内容类型是否有效
    if (contentData.type && !Object.values(ContentType).includes(contentData.type)) {
      return res.status(400).json({
        success: false,
        message: '无效的内容类型'
      });
    }
    
    // 先查询确认是风景类型
    const existingContent = await contentDisplayService.getContentById(id);
    if (!existingContent || existingContent.category !== ContentCategory.SCENERY) {
      return res.status(404).json({
        success: false,
        message: '风景内容不存在'
      });
    }
    
    const content = await contentDisplayService.updateContent(id, contentData, userId);
    
    res.json({
      success: true,
      message: '更新风景内容成功',
      data: content
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '更新风景内容失败',
      error: error.message
    });
  }
};

/**
 * 删除风景内容
 */
export const deleteScenery = async (req: AuthRequest, res: Response) => {
  try {
    const id = req.params.id;
    
    // 先查询确认是风景类型
    const existingContent = await contentDisplayService.getContentById(id);
    if (!existingContent || existingContent.category !== ContentCategory.SCENERY) {
      return res.status(404).json({
        success: false,
        message: '风景内容不存在'
      });
    }
    
    const result = await contentDisplayService.deleteContent(id);
    
    if (!result) {
      return res.status(404).json({
        success: false,
        message: '删除风景内容失败'
      });
    }
    
    res.json({
      success: true,
      message: '删除风景内容成功'
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '删除风景内容失败',
      error: error.message
    });
  }
};

/**
 * 获取风景内容详情
 */
export const getSceneryDetail = async (req: AuthRequest, res: Response) => {
  try {
    const id = req.params.id;
    const content = await contentDisplayService.getContentById(id);
    
    if (!content) {
      return res.status(404).json({
        success: false,
        message: '内容不存在'
      });
    }
    
    // 确认是风景类型
    if (content.category !== ContentCategory.SCENERY) {
      return res.status(404).json({
        success: false,
        message: '风景内容不存在'
      });
    }
    
    res.json({
      success: true,
      data: content
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '获取风景内容详情失败',
      error: error.message
    });
  }
};

// ==================== 活动内容管理接口 ====================

/**
 * 获取活动内容列表
 */
export const getActivityList = async (req: AuthRequest, res: Response) => {
  try {
    const current = Number(req.query.page) || 1;
    const size = Number(req.query.size) || 10;
    const type = req.query.type !== undefined ? Number(req.query.type) : undefined;
    const isActive = req.query.isActive !== undefined ? req.query.isActive === 'true' : undefined;
    const title = req.query.title as string;
    
    const { contents, total } = await contentDisplayService.getContentList({
      page: current,
      pageSize: size,
      category: ContentCategory.ACTIVITY,
      type,
      isActive,
      title
    });
    
    const response: ApiResponse<ContentListResponse> = {
      success: true,
      data: {
        records: contents,
        total,
        size,
        current,
        pages: Math.ceil(total / size)
      }
    };
    
    res.json(response);
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '获取活动内容列表失败',
      error: error.message
    });
  }
};

/**
 * 创建活动内容
 */
export const createActivity = async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.user?.id;
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }
    
    const contentData = req.body;
    
    // 设置固定类别为活动
    contentData.category = ContentCategory.ACTIVITY;
    
    // 验证必填字段
    if (!contentData.type || !contentData.title) {
      return res.status(400).json({
        success: false,
        message: '内容类型和标题为必填项'
      });
    }
    
    // 验证内容类型是否有效
    if (!Object.values(ContentType).includes(contentData.type)) {
      return res.status(400).json({
        success: false,
        message: '无效的内容类型'
      });
    }
    
    // 验证内容类型和URL是否匹配
    if ((contentData.type === ContentType.IMAGE) && !contentData.imageUrl) {
      return res.status(400).json({
        success: false,
        message: '图片类型内容必须提供图片URL'
      });
    }
    
    if (contentData.type === ContentType.VIDEO && !contentData.videoUrl) {
      return res.status(400).json({
        success: false,
        message: '视频类型内容必须提供视频URL'
      });
    }
    
    const content = await contentDisplayService.createContent(contentData, userId);
    
    res.json({
      success: true,
      message: '创建活动内容成功',
      data: content
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '创建活动内容失败',
      error: error.message
    });
  }
};

/**
 * 更新活动内容
 */
export const updateActivity = async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.user?.id;
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }
    
    const id = req.params.id;
    const contentData = req.body;
    
    // 确保不能修改类别
    delete contentData.category;
    
    // 验证内容类型是否有效
    if (contentData.type && !Object.values(ContentType).includes(contentData.type)) {
      return res.status(400).json({
        success: false,
        message: '无效的内容类型'
      });
    }
    
    // 先查询确认是活动类型
    const existingContent = await contentDisplayService.getContentById(id);
    if (!existingContent || existingContent.category !== ContentCategory.ACTIVITY) {
      return res.status(404).json({
        success: false,
        message: '活动内容不存在'
      });
    }
    
    const content = await contentDisplayService.updateContent(id, contentData, userId);
    
    res.json({
      success: true,
      message: '更新活动内容成功',
      data: content
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '更新活动内容失败',
      error: error.message
    });
  }
};

/**
 * 删除活动内容
 */
export const deleteActivity = async (req: AuthRequest, res: Response) => {
  try {
    const id = req.params.id;
    
    // 先查询确认是活动类型
    const existingContent = await contentDisplayService.getContentById(id);
    if (!existingContent || existingContent.category !== ContentCategory.ACTIVITY) {
      return res.status(404).json({
        success: false,
        message: '活动内容不存在'
      });
    }
    
    const result = await contentDisplayService.deleteContent(id);
    
    if (!result) {
      return res.status(404).json({
        success: false,
        message: '删除活动内容失败'
      });
    }
    
    res.json({
      success: true,
      message: '删除活动内容成功'
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '删除活动内容失败',
      error: error.message
    });
  }
};

/**
 * 获取活动内容详情
 */
export const getActivityDetail = async (req: AuthRequest, res: Response) => {
  try {
    const id = req.params.id;
    const content = await contentDisplayService.getContentById(id);
    
    if (!content) {
      return res.status(404).json({
        success: false,
        message: '内容不存在'
      });
    }
    
    // 确认是活动类型
    if (content.category !== ContentCategory.ACTIVITY) {
      return res.status(404).json({
        success: false,
        message: '活动内容不存在'
      });
    }
    
    res.json({
      success: true,
      data: content
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '获取活动内容详情失败',
      error: error.message
    });
  }
};

// ==================== 前台API接口 ====================

/**
 * 前台获取特定类别的内容列表
 */
export const getContentsByCategory = async (req: Request, res: Response) => {
  try {
    const category = Number(req.params.category);
    const limit = Number(req.query.limit) || 10;
    
    // 验证模块类型是否有效
    if (!Object.values(ContentCategory).includes(category)) {
      return res.status(400).json({
        success: false,
        message: '无效的模块类型'
      });
    }
    
    const contents = await contentDisplayService.getContentsByCategory(category, limit);
    
    res.json({
      success: true,
      data: contents
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '获取内容列表失败',
      error: error.message
    });
  }
}; 